<?php

namespace App\Http\Controllers\Admin;

use App\Exports\HousingsExport;
use App\Http\Filters\HousingsFilter;
use App\Models\Housings;
use App\Http\Requests\HousingsRequest;
use App\Http\Resources\HousingsResource;
use App\Models\HousingsEditAddressLog;
use App\Models\HousingsLessee;
use App\Models\HousingsVerifyLog;
use App\Models\Report;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;

class HousingsController extends Controller
{
    public function index(HousingsFilter $filter)
    {
        $housingss = Housings::query()->with('department')
            ->filter($filter)
            ->paginate();

        return $this->ok(HousingsResource::collection($housingss));
    }

    public function create()
    {
        return $this->ok();
    }

    public function store(HousingsRequest $request)
    {
        $inputs = $request->validated();
        $housings = Housings::create($inputs);

        return $this->created(HousingsResource::make($housings));
    }

    public function edit(Request $request,Housings $housings,$id)
    {
        $report = Housings::findOrFail($id);
        return $this->ok(HousingsResource::make($report)->for(HousingsResource::FOR_EDIT)->additional($this->formData($report)));
    }
    protected function formData($report)
    {

        $housingsLessee = HousingsLessee::where("housings_id",$report['id'])
            ->orderByDesc('id')
            ->first();
        return compact('housingsLessee');
    }

    public function update(HousingsRequest $request, Housings $housings, $id)
    {
        $inputs = $request->validated();
        $housings->update($inputs);
        $housings = Housings::findOrFail($id);
        HousingsVerifyLog::create(['housings_id'=>$id,'admin_user_id'=>Auth::id(),'type'=>$inputs['type'],'content'=>isset($inputs['content']) ? $inputs['content'] :'']);
        return $this->created(HousingsResource::make($housings));
    }

    public function destroy(Housings $housings)
    {
        $housings->delete();
        return $this->noContent();
    }

    public function housingseditaddresslog(HousingsRequest $request)
    {
        $requestdata=$request->validated();
        $housings = Housings::findOrFail($requestdata['id']);
        return $this->ok(HousingsResource::make($housings)->additional($this->formDataAddress($housings)));
    }
    public function formDataAddress($housings)
    {
        $housingseditaddresslog = HousingsEditAddressLog::where("housings_id",$housings['id'])
            ->orderByDesc('id')
            ->first();
        return compact('housingseditaddresslog');
    }

    public function export(Report $report)
    {
        $filters = $report->only([
            'ids',
            // ... 其他可能的过滤条件
        ]);
        return Excel::download(new HousingsExport($filters), '房屋报备.xlsx');
    }
}
